package demo.main;

import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.report;
import static net.sf.dynamicreports.report.builder.DynamicReports.type;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.dynamicreports.report.exception.DRException;

import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

public class ColumnReport extends MutiReport {
	private Connection conn;
	
	@At("/getColumnReport")
	@Ok("json")
	public String getColumnReport(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("getColumnReport");
		build(request, response);
		return resultResult;
	}
	
	protected void build(HttpServletRequest request, HttpServletResponse response) {
		try {
			reportBuilder = report()
					  .setTemplate(Templates.reportTemplate)
					  .columns(
					  	col.column("产品",       "item",      type.stringType()).setStyle(Templates.rootStyle),
					  	col.column("数量",   "quantity",  type.integerType()),
					  	col.column("单价", "unitprice", type.bigDecimalType()))
					  .title(Templates.createTitleComponent(""))
					  .pageFooter(Templates.footerComponent)
					  .setDataSource("SELECT * FROM product", getConn());

			setResult(reportBuilder.toJasperPrint(), request, response);
		} catch (DRException e) {
			e.printStackTrace();
		}
	}
	private Connection getConn() {
		if (conn == null) {
			initDatabase();
		}
		return conn;
	}

	private void initDatabase() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = java.sql.DriverManager
					.getConnection(
							"jdbc:mysql://localhost:3308/test",
							"root", "4751603");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	};
}
